package ${basepackage}.framework.base.intecepter;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ${basepackage}.framework.base.util.AppConstant;
import com.mysql.jdbc.StringUtils;

<#include "/author.include">
public class CheckLoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handle) throws Exception {

		AuthRequired authRequiredMethod = null;
		if(handle.getClass().isAssignableFrom(HandlerMethod.class)){
			authRequiredMethod = ((HandlerMethod)handle).getMethodAnnotation(AuthRequired.class);
		}
			if((authRequiredMethod == null || authRequiredMethod.validate() == false) ){
				return true;
			}
			String contextPath=request.getContextPath();
			String	url=request.getServletPath().toString();
			HttpSession session = request.getSession();
			String user = (String) session.getAttribute(AppConstant.SESSION_USER_ID);
			if(StringUtils.isNullOrEmpty(user)){
				response.sendRedirect(contextPath + "/account/login?redirectURL=" + URLEncoder.encode(url));
				return false;
			}
	
		
		
		
		return true;
	}

}
